package controllers

import (
	"SimpleDockerPanel/controllers/service"
	"SimpleDockerPanel/controllers/service/models"
	"SimpleDockerPanel/pkg/logger"
	r "SimpleDockerPanel/pkg/resp"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"strconv"
)

type UserController struct{}

func (u UserController) Register(c *gin.Context) {
	// 用户名 密码 确认密码
	param := &models.UserRegister{}
	err := c.BindJSON(param)
	if err != nil {
		r.Fail(c, r.FAIL_SERVER_CODE, r.FAIL_PARAM_ERROR)
		return
	}
	if param.Username == "" || param.Password == "" || param.RePassword == "" {
		r.Fail(c, r.FAIL_SERVER_CODE, r.FAIL_PARAM_NOT_EXIST)
		return
	}
	if param.Password != param.RePassword {
		r.Fail(c, r.FAIL_SERVER_CODE, r.FAIL_REGISTER_PASSWORD_ERROR)
		return
	}
	err = service.Register(param.Username, param.Password, param.Email)
	if err != nil {
		logger.Write(err.Error(), "register")
		r.Fail(c, r.FAIL_SERVER_CODE, r.FAIL_REGISTER_ERROR)
		return
	}
	r.Success(c, r.SUCCESS_CODE, r.SUCCESS_REGISTER)
	return
}

func (u UserController) GetUserInfo(c *gin.Context) {
	r.SuccessData(c, 200, "get user info", "name: 123, age: 2", 1)
}

func (u UserController) Login(c *gin.Context) {
	param := &models.UserLogin{}
	err := c.BindJSON(param)
	if err != nil {
		r.Fail(c, r.FAIL_SERVER_CODE, r.FAIL_PARAM_ERROR)
		return
	}
	user, err := service.Login(param.Username, param.Password)
	if err != nil {
		r.Fail(c, r.FAIL_SERVER_CODE, err.Error())
		return
	}
	session := sessions.Default(c)
	session.Set("Login"+strconv.Itoa(user.Id), user.Id)
	session.Save()
	r.SuccessData(c, r.SUCCESS_CODE, r.SUCCESS_LOGIN, user, 0)
}
